package com.ecloud.common;

import com.alibaba.fastjson.JSON;
import com.ecloud.common.exception.JsonResultException;
import com.ecloud.common.exception.ServerException;
import lombok.Builder;
import lombok.Data;

import java.io.Serializable;
import java.util.List;

/**
 * Json返回对象
 *
 * @author Squbi
 * @date 2021/3/29 12:36
 */
@Data
@Builder
public class JsonResult implements Serializable {
    private boolean success;
    private int code;
    private String message;
    private Object data;

    // --- 构造方法 ---
    public static JsonResult success(String message, Object data) {
        return JsonResult.builder()
                .success(true)
                .code(ResultEnum.SUCCESS.getCode())
                .message(message)
                .data(data)
                .build();
    }

    public static JsonResult success(Object data) {
        return success(ResultEnum.SUCCESS.getMsg(), data);
    }

    public static JsonResult success() {
        return success(null);
    }

    public static JsonResult failed(int code, String message) {
        return JsonResult.builder()
                .success(false)
                .code(code)
                .message(message)
                .data(null)
                .build();
    }

    public static JsonResult failed(ResultEnum resultEnum) {
        return JsonResult.builder()
                .success(false)
                .code(resultEnum.getCode())
                .message(resultEnum.getMsg())
                .data(null)
                .build();
    }

    public static JsonResult failed(ResultEnum resultEnum, String msg) {
        return JsonResult.builder()
                .success(false)
                .code(resultEnum.getCode())
                .message(resultEnum.getMsg())
                .data(msg)
                .build();
    }

    // --- unpack ---

    public Object unwrap() {
        if (!success) {
            throw new JsonResultException(this);
        } else {
            return data;
        }
    }


    public <T> T unpackObject() {
        Object data = unwrap();
        return (T) data;
    }

    public <T> List<T> unpackArray(Class<T> dataClass) {
        Object data = unwrap();
        if (data instanceof List) {
            String json = JSON.toJSONString(data);
            return JSON.parseArray(json, dataClass);
        } else {
            throw new ServerException(ResultEnum.ARGS_ERR);
        }
    }

    public String toStringExData() {
        String data = this.data == null ? "null" : "some";
        return "JsonResult{" +
                "success=" + success +
                ", code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
